package org.Iter2.Presentacion;

import org.Iter2.Dominio.GestorUsuarios;
import org.Iter2.Dominio.Usuario;
import org.Iter2.Dominio.UsuarioConPrivilegios;
import org.Iter2.Dominio.UsuarioSinPrivilegios;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

import java.awt.Dimension;

import javax.swing.JList;

import java.awt.Component;

import javax.swing.Box;

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.HeadlessException;
import java.awt.Insets;

import javax.swing.border.TitledBorder;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.ImageIcon;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Enumeration;

import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.border.EtchedBorder;

import java.awt.Color;

public class VentanaGestorUsuarios extends JFrame {

	private JPanel contentPane;
	private final Component verticalStrut = Box.createVerticalStrut(20);
	private final JPanel pnlGestorUsuarios = new JPanel();
	private final JScrollPane scrollPane = new JScrollPane();
	private final Component horizontalStrut = Box.createHorizontalStrut(20);
	private final JPanel panel = new JPanel();
	private final JLabel lblIdentificador = new JLabel("Identificador:");
	private final JLabel lblContrasea = new JLabel("Contrase\u00F1a:");
	private final JLabel txtConstrasena = new JLabel("Nombre:");
	private final JLabel lblApellidos = new JLabel("Apellidos:");
	private final Component horizontalStrut_1 = Box.createHorizontalStrut(20);
	private final Component verticalStrut_1 = Box.createVerticalStrut(20);
	private final JTextField txtIdentificador = new JTextField();
	private final JTextField txtPass = new JTextField();
	private final JTextField txtNombre = new JTextField();
	private final JTextField txtApellidos = new JTextField();
	private final JLabel lblPrivilegios = new JLabel("Usuario con privilegios:");
	private final JCheckBox chbPrivilegios = new JCheckBox("");
	private final JPanel panel_1 = new JPanel();
	private final Component horizontalStrut_2 = Box.createHorizontalStrut(20);
	private final JButton btnAadir = new JButton("A\u00F1adir");
	private final JButton btnModificar = new JButton("Modificar");
	private final JButton btnEliminar = new JButton("Eliminar");
	private final JPanel panel_2 = new JPanel();
	private final JPanel pnlLogo = new JPanel();
	private final JLabel lblLogoUsuarios = new JLabel("");
	private GestorUsuarios gu;
	DefaultListModel<String> modeloLista = new DefaultListModel<String>();
	private final JList<String> listUsuarios = new JList<String>();
	private final JButton btnVolver = new JButton("Volver");
	private String tipo;
	
	/**
	 * Create the frame.
	 */
	public VentanaGestorUsuarios() {
		
		try {
			gu=new GestorUsuarios();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		setPreferredSize(new Dimension(660, 450));
		setTitle("findpersons - Gestor de Usuarios");
		txtApellidos.setColumns(10);
		txtNombre.setColumns(10);
		txtPass.setColumns(10);
		txtIdentificador.setColumns(10);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 660, 450);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		pnlLogo.setPreferredSize(new Dimension(10, 90));
		
		contentPane.add(pnlLogo, BorderLayout.NORTH);
		pnlLogo.setLayout(null);
		lblLogoUsuarios.setIcon(new ImageIcon(VentanaGestorUsuarios.class.getResource("/org/Iter2/Recursos/logoUsuarios.png")));
		lblLogoUsuarios.setBounds(6, 6, 420, 72);
		
		pnlLogo.add(lblLogoUsuarios);
		btnVolver.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
				VentanaPrincipal vp=new VentanaPrincipal();
				vp.mostrar(tipo);
				
			}
		});
		btnVolver.setBounds(501, 49, 117, 29);
		
		pnlLogo.add(btnVolver);
		listUsuarios.setModel(modeloLista);
		listUsuarios.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				txtIdentificador.setText(listUsuarios.getSelectedValue());
				txtPass.setText(gu.getTablaUsuarios().get(listUsuarios.getSelectedValue()).getPassword());
				txtNombre.setText(gu.getTablaUsuarios().get(listUsuarios.getSelectedValue()).getNombre());
				txtApellidos.setText(gu.getTablaUsuarios().get(listUsuarios.getSelectedValue()).getApellidos());
				if((gu.getTablaUsuarios().get(listUsuarios.getSelectedValue()).getTipo()).equalsIgnoreCase("administrador")){
					chbPrivilegios.setSelected(true);
				}else{
					chbPrivilegios.setSelected(false);
				}
			
				
			}
		});
		
		contentPane.add(verticalStrut, BorderLayout.SOUTH);
		
		contentPane.add(pnlGestorUsuarios, BorderLayout.CENTER);
		GridBagLayout gbl_pnlGestorUsuarios = new GridBagLayout();
		gbl_pnlGestorUsuarios.columnWidths = new int[]{0, 128, 420, 0, 0};
		gbl_pnlGestorUsuarios.rowHeights = new int[]{0, 0};
		gbl_pnlGestorUsuarios.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
		gbl_pnlGestorUsuarios.rowWeights = new double[]{1.0, Double.MIN_VALUE};
		pnlGestorUsuarios.setLayout(gbl_pnlGestorUsuarios);
		
		GridBagConstraints gbc_horizontalStrut = new GridBagConstraints();
		gbc_horizontalStrut.insets = new Insets(0, 0, 0, 5);
		gbc_horizontalStrut.gridx = 0;
		gbc_horizontalStrut.gridy = 0;
		pnlGestorUsuarios.add(horizontalStrut, gbc_horizontalStrut);
		
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.insets = new Insets(0, 0, 0, 5);
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridx = 1;
		gbc_scrollPane.gridy = 0;
		scrollPane.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Usuarios", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
		scrollPane.setPreferredSize(new Dimension(175, 4));
		pnlGestorUsuarios.add(scrollPane, gbc_scrollPane);
		scrollPane.setViewportView(listUsuarios);
		
	    Enumeration<String> e = gu.getTablaUsuarios().keys();
	    while(e.hasMoreElements()){
	    	modeloLista.addElement(gu.getTablaUsuarios().get(e.nextElement()).getId());
	    }
		
		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(0, 0, 0, 5);
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.gridx = 2;
		gbc_panel.gridy = 0;
		panel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Ficha Usuario", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
		pnlGestorUsuarios.add(panel, gbc_panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.columnWidths = new int[]{0, 110, 178, 0, 0};
		gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
		gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		panel.setLayout(gbl_panel);
		
		GridBagConstraints gbc_verticalStrut_1 = new GridBagConstraints();
		gbc_verticalStrut_1.insets = new Insets(0, 0, 5, 5);
		gbc_verticalStrut_1.gridx = 1;
		gbc_verticalStrut_1.gridy = 0;
		panel.add(verticalStrut_1, gbc_verticalStrut_1);
		
		GridBagConstraints gbc_horizontalStrut_1 = new GridBagConstraints();
		gbc_horizontalStrut_1.insets = new Insets(0, 0, 5, 5);
		gbc_horizontalStrut_1.gridx = 0;
		gbc_horizontalStrut_1.gridy = 1;
		panel.add(horizontalStrut_1, gbc_horizontalStrut_1);
		
		GridBagConstraints gbc_lblIdentificador = new GridBagConstraints();
		gbc_lblIdentificador.anchor = GridBagConstraints.WEST;
		gbc_lblIdentificador.insets = new Insets(0, 0, 5, 5);
		gbc_lblIdentificador.gridx = 1;
		gbc_lblIdentificador.gridy = 1;
		panel.add(lblIdentificador, gbc_lblIdentificador);
		
		GridBagConstraints gbc_txtIdentificador = new GridBagConstraints();
		gbc_txtIdentificador.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtIdentificador.insets = new Insets(0, 0, 5, 5);
		gbc_txtIdentificador.gridx = 2;
		gbc_txtIdentificador.gridy = 1;
		panel.add(txtIdentificador, gbc_txtIdentificador);
		
		GridBagConstraints gbc_lblContrasea = new GridBagConstraints();
		gbc_lblContrasea.anchor = GridBagConstraints.WEST;
		gbc_lblContrasea.insets = new Insets(0, 0, 5, 5);
		gbc_lblContrasea.gridx = 1;
		gbc_lblContrasea.gridy = 2;
		panel.add(lblContrasea, gbc_lblContrasea);
		
		GridBagConstraints gbc_txtPass = new GridBagConstraints();
		gbc_txtPass.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtPass.insets = new Insets(0, 0, 5, 5);
		gbc_txtPass.gridx = 2;
		gbc_txtPass.gridy = 2;
		panel.add(txtPass, gbc_txtPass);
		
		GridBagConstraints gbc_txtConstrasena = new GridBagConstraints();
		gbc_txtConstrasena.anchor = GridBagConstraints.WEST;
		gbc_txtConstrasena.insets = new Insets(0, 0, 5, 5);
		gbc_txtConstrasena.gridx = 1;
		gbc_txtConstrasena.gridy = 3;
		panel.add(txtConstrasena, gbc_txtConstrasena);
		
		GridBagConstraints gbc_txtNombre = new GridBagConstraints();
		gbc_txtNombre.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtNombre.insets = new Insets(0, 0, 5, 5);
		gbc_txtNombre.gridx = 2;
		gbc_txtNombre.gridy = 3;
		panel.add(txtNombre, gbc_txtNombre);
		
		GridBagConstraints gbc_lblApellidos = new GridBagConstraints();
		gbc_lblApellidos.insets = new Insets(0, 0, 5, 5);
		gbc_lblApellidos.anchor = GridBagConstraints.WEST;
		gbc_lblApellidos.gridx = 1;
		gbc_lblApellidos.gridy = 4;
		panel.add(lblApellidos, gbc_lblApellidos);
		
		GridBagConstraints gbc_txtApellidos = new GridBagConstraints();
		gbc_txtApellidos.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtApellidos.insets = new Insets(0, 0, 5, 5);
		gbc_txtApellidos.gridx = 2;
		gbc_txtApellidos.gridy = 4;
		panel.add(txtApellidos, gbc_txtApellidos);
		
		GridBagConstraints gbc_panel_2 = new GridBagConstraints();
		gbc_panel_2.gridwidth = 3;
		gbc_panel_2.insets = new Insets(0, 0, 5, 5);
		gbc_panel_2.fill = GridBagConstraints.HORIZONTAL;
		gbc_panel_2.gridx = 1;
		gbc_panel_2.gridy = 5;
		panel.add(panel_2, gbc_panel_2);
		GridBagLayout gbl_panel_2 = new GridBagLayout();
		gbl_panel_2.columnWidths = new int[]{98, 149, 28, 0};
		gbl_panel_2.rowHeights = new int[]{23, 0};
		gbl_panel_2.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
		gbl_panel_2.rowWeights = new double[]{0.0, Double.MIN_VALUE};
		panel_2.setLayout(gbl_panel_2);
		GridBagConstraints gbc_lblPrivilegios = new GridBagConstraints();
		gbc_lblPrivilegios.anchor = GridBagConstraints.WEST;
		gbc_lblPrivilegios.insets = new Insets(0, 0, 0, 5);
		gbc_lblPrivilegios.gridx = 0;
		gbc_lblPrivilegios.gridy = 0;
		panel_2.add(lblPrivilegios, gbc_lblPrivilegios);
		GridBagConstraints gbc_chbPrivilegios = new GridBagConstraints();
		gbc_chbPrivilegios.insets = new Insets(0, 0, 0, 5);
		gbc_chbPrivilegios.anchor = GridBagConstraints.NORTHWEST;
		gbc_chbPrivilegios.gridx = 1;
		gbc_chbPrivilegios.gridy = 0;
		panel_2.add(chbPrivilegios, gbc_chbPrivilegios);
		panel_1.setLayout(null);
		
		GridBagConstraints gbc_panel_1 = new GridBagConstraints();
		gbc_panel_1.gridwidth = 4;
		gbc_panel_1.fill = GridBagConstraints.BOTH;
		gbc_panel_1.gridx = 0;
		gbc_panel_1.gridy = 6;
		panel.add(panel_1, gbc_panel_1);
		
		
		btnAadir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String privilegios="";
				Usuario user;
				if(txtIdentificador.getText()!=null&&!txtIdentificador.getText().equals("")&&txtPass.getText()!=null&&!txtPass.getText().equals("")&&txtNombre.getText()!=null&&!txtNombre.getText().equals("")&&txtApellidos.getText()!=null&&!txtApellidos.getText().equals("")){
					if(chbPrivilegios.isSelected()){
						privilegios="administrador";
						user=new UsuarioConPrivilegios(txtIdentificador.getText(),txtPass.getText(),txtNombre.getText(),txtApellidos.getText(),privilegios);
					}else{
						user=new UsuarioSinPrivilegios(txtIdentificador.getText(),txtPass.getText(),txtNombre.getText(),txtApellidos.getText(),privilegios);		
					}
					try {
						if(gu.addUsuario(user)){
							modeloLista.addElement(txtIdentificador.getText());
						}else{
							JOptionPane.showMessageDialog(null, "El identificador ya existe.");
						}
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
				}else{
					JOptionPane.showMessageDialog(null, "No puede dejar ningun campo vacio.");
				}

			}
		});
		btnAadir.setBounds(16, 31, 117, 29);
		
		panel_1.add(btnAadir);
		btnModificar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			
				if (listUsuarios.getSelectedValue() == null) {
					JOptionPane.showMessageDialog(null, "Debe seleccionar un usuario.");
				}else{
				String privilegios=" ";
				String id=listUsuarios.getSelectedValue();
				int index = listUsuarios.getSelectedIndex();
				int selectedIndex = calcularIndex(index,modeloLista.size());
				Usuario user;
				if(txtIdentificador.getText()!=null&&!txtIdentificador.getText().equals("")&&txtPass.getText()!=null&&!txtPass.getText().equals("")&&txtNombre.getText()!=null&&!txtNombre.getText().equals("")&&txtApellidos.getText()!=null&&!txtApellidos.getText().equals("")){
					if(chbPrivilegios.isSelected()){
						privilegios="administrador";
						user=new UsuarioConPrivilegios(txtIdentificador.getText(),txtPass.getText(),txtNombre.getText(),txtApellidos.getText(),privilegios);
					}else{
						user=new UsuarioSinPrivilegios(txtIdentificador.getText(),txtPass.getText(),txtNombre.getText(),txtApellidos.getText(),privilegios);		
					}
					
					try {
						if(gu.modificarUsuario(id,user)){
							gu.consultarUsuarios();
							
							listUsuarios.setSelectedIndex(selectedIndex);	
							modeloLista.addElement(user.getId());
							
							
							modeloLista.remove(index);
							scrollPane.revalidate();
						}else{
							JOptionPane.showMessageDialog(null, "No es posible modificar el usuario.");
						}
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				}else{
					JOptionPane.showMessageDialog(null, "No puede dejar ningun campo vacio.");
				}
			}
				
			}
		});
		btnModificar.setBounds(145, 31, 117, 29);
		
		panel_1.add(btnModificar);
		btnEliminar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (listUsuarios.getSelectedValue() == null) {
					JOptionPane.showMessageDialog(null, "Debe seleccionar un usuario.");
				}else{
					String id=listUsuarios.getSelectedValue();
					int index = listUsuarios.getSelectedIndex();
					int selectedIndex = calcularIndex(index,modeloLista.size());
					try {
						if(gu.eliminarUsuario(id)){
							listUsuarios.setSelectedIndex(selectedIndex);
							modeloLista.remove(index);
							gu.consultarUsuarios();
							scrollPane.revalidate();
						}else{
							JOptionPane.showMessageDialog(null, "No se puede eliminar el usuario, es necesario tener al menos un usuario administrador.");
						}
					} catch (HeadlessException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		btnEliminar.setBounds(266, 31, 117, 29);
		
		panel_1.add(btnEliminar);
		
		GridBagConstraints gbc_horizontalStrut_2 = new GridBagConstraints();
		gbc_horizontalStrut_2.gridx = 3;
		gbc_horizontalStrut_2.gridy = 0;
		pnlGestorUsuarios.add(horizontalStrut_2, gbc_horizontalStrut_2);
	}
	public int calcularIndex(int index,int size){
		int ind=0;
		if(index>=0&&index<size-1){
			ind=index+1;	
		}else if(index==size-1){
			ind=size-2;
		}
		return ind;
	}
    public boolean mostrar(String admin)
    {	
    	boolean resultado=false;
    	tipo=admin;
    	if(tipo.equalsIgnoreCase("administrador")){
    		 setVisible(true);
    	     resultado= true;	
    	}
    	return resultado;
       
    }
}
